<template>
	<div>
		<!-- 		用户信息 个人信息
		//  数据回填  -->
		<button @click="$router.back()">
			返回
		</button>
		<van-cell>
			<van-field v-model="userInfoForm.nickname">

			</van-field>
		</van-cell>
		<van-cell>
			<label for="file">
				<van-image :src="userInfoForm.avatar" width="50px" height="50"></van-image>
			</label>

			<input type="file" hidden id="file" @change="uploadFile">
		</van-cell>

		<van-cell>
			{{userInfoForm.sex}}
			<van-radio-group v-model="userInfoForm.sex">
				<van-radio name="男">男</van-radio>
				<van-radio name="女">女</van-radio>
				<van-radio name="">未设置</van-radio>
			</van-radio-group>

		</van-cell>

		<van-field readonly clickable name="picker" :value="userInfoForm.birthday" label="选择出生日期" placeholder="选择出生日期"
			@click="showPicker = true" />
		<van-popup v-model="showPicker" position="bottom">

			<van-datetime-picker v-model="currentDate" type="date" title="选择年月日" :min-date="minDate" :max-date="maxDate"
				@confirm="dateConfirm" />


		</van-popup>

		<button @click="sumbit">提交</button>

	</div>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	import {
		Field,
		RadioGroup,
		Radio,
		Popup,
		DatetimePicker
	} from 'vant'
	import {
		timeFormat
	} from '@/utils/timeform.js'
	import {
		uploadFile
	} from '@/api/upload'
	import {
		editUserInfo
	} from '@/api/user'
	export default {
		name: "UserInfo",
		components: {
			[Field.name]: Field,
			[RadioGroup.name]: RadioGroup,
			[Radio.name]: Radio,
			[Popup.name]: Popup,
			[DatetimePicker.name]: DatetimePicker,
		},
		data() {
			return {
				userInfoForm: {},
				showPicker: false,
				minDate: new Date(1920, 0, 1),
				maxDate: new Date(),
				currentDate: null
			}
		},
		computed: {
			...mapState('user', ['userInfo', 'uid'])
		},
		watch: {
			userInfo: {
				immediate: true,
				handler(val) {
					let {
						nickname,
						avatar,
						birthday,
						sex
					} = val;
					this.userInfoForm = {
						nickname,
						avatar,
						birthday,
						sex
					};
					this.currentDate = birthday ? new Date(birthday) : new Date(2000, 0, 1)
				}
			},


		},
		methods: {
			uploadFile(e) {
				let file = e.target.files[0];
				uploadFile(file).then(img => {
					console.log(img)
					this.userInfoForm.avatar = img
				})
			},
			dateConfirm(e) {
				this.userInfoForm.birthday = timeFormat(+e)
				this.showPicker = false
			},
			sumbit() {
				let {
					userInfoForm,
					uid
				} = this;
				userInfoForm.uid = uid
				editUserInfo(userInfoForm).then(res => {
					console.log(res)
					this.$toast(res.msg)

					if (res.code == 0) {

						this.$store.commit('user/setUserInfo', userInfoForm)
						setTimeout(v => {
							this.$router.back()
						}, 1000)
					}

				})
			}
		}

	}
</script>

<style>
</style>
